import { computed, onMounted, watch } from "vue";
import { useStorageStore } from "src/stores/storage";
import { useUserStore } from "src/stores/user";
// import { dcFrontendDefault } from 'src/settings'
import { useI18n } from "vue-i18n";
import { Quasar } from "quasar";
import useCommon from "src/composables/useCommon";
import { ref } from "vue";

// 动态更改网站标题和favicon，在MainLayout中调用
export default function useDocument() {
  const storageStore = useStorageStore();
  const userStore = useUserStore();
  const dcFrontEnd = computed(() => storageStore.GetDcFrontend());
  const language = computed(() => userStore.GetLanguage());
  const { DcFallbackFrontend } = useCommon();

  watch(dcFrontEnd, (newValue) => {
    document.title = newValue.subTitle;
    createLink();
  });

  onMounted(async () => {
    document.title = dcFrontEnd.value.subTitle || DcFallbackFrontend.subTitle;
    createLink();
    const { locale } = useI18n({ useScope: "global" });
    locale.value = language.value;
    // await import(
    //   /* webpackInclude: /(zh-CN|en-US)\.js$/ */
    //   "quasar/lang/" + language.value
    // ).then((lang) => {
    //   // ! NOTICE ssrContext param:
    //   Quasar.lang.set(lang.default);
    // });
  });

  const createLink = () => {
    const toDelete = document.getElementsByName("dc-link-href");
    if (toDelete && toDelete.length) {
      document.getElementsByTagName("head")[0].removeChild(toDelete[0]);
    }
    const dcLink = document.createElement("link");
    dcLink.type = "image/ico";
    dcLink.rel = "icon";
    dcLink.setAttribute("name", "dc-link-href");
    if (dcFrontEnd.value.favicon && dcFrontEnd.value.favicon !== "") {
      const favicon = process.env.API + dcFrontEnd.value.favicon.substring(11);
      dcLink.href = favicon;
    } else {
      dcLink.href = "favicon.ico";
    }
    document.getElementsByTagName("head")[0].appendChild(dcLink);
  };
  return {
    createLink,
  };
}
